//
//  ProDetailViewController.m
//  LiWuShuo
//
//  Created by 袁小航 on 14/11/19.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ProDetailViewController.h"
#import "ProDetail.h"
#import "Define.h"
#import "AppDelegate.h"
#import "Collect.h"
#import "ViewController.h"
#import <UIImageView+AFNetworking.h>

@interface ProDetailViewController ()<UIScrollViewDelegate, UIWebViewDelegate>

//创建视图
@property(nonatomic, retain) ProDetail *proDetail;

//定义NSManagedObjectContext类型对象
@property(nonatomic, strong) NSManagedObjectContext *managedObjectContext;
//coreData中的数据
@property(nonatomic, retain) NSArray *DBData;
//不论成功与否 收藏后都弹出的alert
@property(nonatomic, retain) UIAlertView *CollAlert;
@property(nonatomic, retain) UIAlertView *CollFailAlert;
//复制本页链接弹出的窗口
@property(nonatomic, retain) UIAlertView *shareAlert;

//创建视图正在加载的时候的小菊花
@property(nonatomic, retain) UIActivityIndicatorView *activityView;

@end

@implementation ProDetailViewController

- (void)viewWillAppear:(BOOL)animated
{
    
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
//    将商品详情页最上方的图片 设置成前一页的图片
    if (_proDetailImage != nil) {
        [_proDetail.detailBackImage setImageWithURL:[NSURL URLWithString:_proDetailImage] placeholderImage:nil];
        _proDetail.detailBackImage.contentMode = UIViewContentModeScaleAspectFill;
    } else {
        _proDetailImage = @"http://fc.topit.me/c/b6/d8/11292308056cbd8b6cl.jpg";
        [_proDetail.detailBackImage setImageWithURL:[NSURL URLWithString:_proDetailImage] placeholderImage:nil];
        _proDetail.detailBackImage.contentMode = UIViewContentModeScaleAspectFill;
    }
    if (_proDetailInfo != nil) {
        _proDetail.detailNavTitle.text = _proDetailInfo;
        _proDetail.detailBackImageInfo.text = _proDetailInfo;
    } else {
        _proDetailInfo = @"推荐";
        NSString *str = @"精心选择，首页推荐";
        _proDetail.detailNavTitle.text = str;
        _proDetail.detailBackImageInfo.text = str;
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
//    为了隐藏从商品详情页返回时，navigation自带的返回按钮
    self.navigationController.navigationBar.tintColor = [UIColor clearColor];
    
//    导入AppDelegate delegate
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    self.managedObjectContext = delegate.managedObjectContext;
    
    //    创建ProDetailView
    [self createProDetailView];
    
    //    创建了自定义的返回按钮
    [self createBackButton];
    
}


#pragma mark - 创建自定义返回按钮
- (void)createBackButton
{
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(DET_BACK_BUTTON_X, DET_BACK_BUTTON_Y, DET_BACK_BUTTON_WIDTH, DET_BACK_BUTTON_WIDTH);
    [back setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backPageAction:) forControlEvents:UIControlEventTouchUpInside];
    [_proDetail.detailNav addSubview:back];
}

#pragma mark - 自定义的返回按钮的 响应方法
- (void)backPageAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark - 创建ProDetailView
- (void)createProDetailView
{
    self.proDetail = [[ProDetail alloc]initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT)];
    _proDetail.proDetailWebView.scrollView.delegate = self;
    _proDetail.proDetailWebView.delegate = self;
    [self.view addSubview:_proDetail];
    [self.view bringSubviewToFront:self.proDetail];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_proDetailUrl]];
    [_proDetail.proDetailWebView loadRequest:request];
    
//    设置收藏按钮的响应事件
    [_proDetail.detailTabCollButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    设置分享按钮的响应事件
    [_proDetail.detailTabShareButton addTarget:self action:@selector(shareButtonAction) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark - collectButton的响应事件
- (void)collectButtonAction:(UIButton *)sender
{
    if (_proDetailImage != nil) {
    }
    //    获取coredata中所有数据
    [self selectDataFromCoredata];
    
    for (Collect *coll in _DBData) {
        if ([coll.info isEqualToString:_proDetailInfo]) {
            //            当收藏失败的时候  弹出提示框
            self.CollFailAlert = [[UIAlertView alloc]initWithTitle:@"" message:@"已取消收藏该礼物！" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
            [_CollFailAlert show];
        //            提示框1秒后自动消失
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:NO];
            
//            发现与数据库中的数据相同
            NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Collect"];
//            查出该数据
            request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"info = '%@'", _proDetailInfo]];
//            将该数据保存到临时数组中
            NSArray *temp = [self.managedObjectContext executeFetchRequest:request error:nil];
//            定义一个新的Collect类型的对象  用来保存查到的数据
            Collect *tempColl = temp[0];
//            从数据库中删除该元素
            if (tempColl != nil) {
                [self.managedObjectContext deleteObject:tempColl];
                [self.managedObjectContext save:nil];
            }
            return;
        }
    }
    //    添加到数据库
    NSEntityDescription *collEntity = [NSEntityDescription entityForName:@"Collect" inManagedObjectContext:self.managedObjectContext];
    //    创建Collect 对象
    Collect *coll = [[Collect alloc]initWithEntity:collEntity insertIntoManagedObjectContext:self.managedObjectContext];
    //    对Collect对象赋值
    coll.info = _proDetailInfo;
    coll.url = _proDetailUrl;
    coll.image = _proDetailImage;
    
    //    保存到数据库
    [self.managedObjectContext save:nil];
    
    //    显示“收藏成功”
    self.CollAlert = [[UIAlertView alloc]initWithTitle:@"" message:@"收藏成功!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [_CollAlert show];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:NO];
    
}
#pragma mark - 一秒之后 “收藏成功”消失
- (void)timerAction
{
    [_CollFailAlert dismissWithClickedButtonIndex:0 animated:YES];
    [_CollAlert dismissWithClickedButtonIndex:0 animated:YES];
    [_shareAlert dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark - 获取数据库中的持久化数据
- (void)selectDataFromCoredata
{
    //    获取coredata中所有的数据
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Collect"];
    self.DBData = [self.managedObjectContext executeFetchRequest:request error:nil];
}

#pragma mark - 分享按钮的响应事件
- (void)shareButtonAction
{
    UIPasteboard *copyUrl = [UIPasteboard generalPasteboard];
    copyUrl.persistent = NO;
    copyUrl.URL = [NSURL URLWithString:_proDetailUrl];
    self.shareAlert = [[UIAlertView alloc]initWithTitle:@"分享" message:@"已复制本页链接，快去分享给朋友吧~" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [_shareAlert show];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:NO];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat content = scrollView.contentOffset.y;
    CGRect newFrame = _proDetail.proDetailWebView.frame;
    
    if (content < DET_CONTENT_Y) {
//        在webview往下拉的时候，让图片跟着走
        newFrame.origin.y = DET_IMAGEVIEW_ORIGIN_Y + DET_CONTENT_Y - (140 + content);
        _proDetail.detailBackImage.frame = newFrame;
    } else if (content >= DET_CONTENT_Y && content < DET_DETAIL_HIGHT) {
//        在webview往上滑的时候，让图片跟着走
        newFrame.origin.y = DET_IMAGEVIEW_ORIGIN_Y + DET_CONTENT_Y - (140 + content);
        _proDetail.detailBackImage.frame = newFrame;
//        让navTitle显示的时候、 Info隐藏
        if (content <= -60) {
            _proDetail.detailBackImageInfo.alpha = -((content + 60) / 80);
            _proDetail.detailNavTitle.alpha = 1 + ((content + 60) / 80);
        }
    }
}

#pragma mark - webView的delegate
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//    UIView *loadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT)];
//    loadView.tag = 108;
//    loadView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.6];
//    [self.view addSubview:loadView];
    
    self.activityView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 32, 32)];
    _activityView.center = self.view.center;
    [_activityView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:_activityView];
    
    [_activityView startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [_activityView stopAnimating];
//    UIView *loadView = (UIView *)[self.view viewWithTag:108];
//    [loadView removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
